import csv
import json
import re

import time
import traceback

from bs4 import BeautifulSoup
from tomorrow import threads

from common.request import seleniumutil, requestutil
from config import config


# /manage/kefu_clients/index.html
# /manage/kefu_againclientslist/index.html
def to_target_page(browser, tag):
    to_main(browser)
    panals = browser.find_elements_by_css_selector(".tabs-panels .panel")
    for panal in panals:
        to_main(browser)
        if tag in panal.get_attribute("outerHTML"):
            iframe = panal.find_element_by_tag_name("iframe")
            browser.switch_to.frame(iframe)


def switch_selected_frame(browser):
    to_main(browser)
    panals = browser.find_elements_by_css_selector(".tabs-panels .panel")
    for panal in panals:
        if "<div class=\"panel\" style=\"display: block; width:" in panal.get_attribute("outerHTML"):
            iframe = panal.find_element_by_tag_name("iframe")
            browser.switch_to.frame(iframe)


def to_last_page(browser):
    to_main(browser)
    browser.find_element_by_css_selector("#tabs > div.tabs-header > div.tabs-wrap > ul > li.tabs-last").click()
    browser.switch_to.frame("iframeRightId")
    switch_selected_frame(browser)


def close_last_page(browser):
    to_main(browser)
    browser.find_element_by_css_selector(
        "#tabs > div.tabs-header > div.tabs-wrap > ul > li.tabs-last > a.tabs-close").click()


def to_main(browser):
    browser.switch_to.default_content()


def get_text(soup, selector):
    try:
        aaa = ""
        selector = selector.replace("nth-child", "nth-of-type")
        # t0 = time.clock()
        fff = soup.select(selector)
        if fff:
            aaa = fff[0].text

        # txt = browser.find_element_by_css_selector(selector).text
        # t1 = time.clock()
        # print("%s: %s s" % (selector, (str(t1 - t0))))

        return aaa
    except Exception as e:
        if "no such element" in str(e):
            return ""
        return "获取失败" + str(e)


def click_menu(browser, menu_name):
    menus = browser.find_elements_by_css_selector("#tree > li >.tree-node > span.tree-title")
    for m in menus:
        if menu_name in m.text:
            m.click()
            break


我的客户_data_csvfile = open(config.PATH_DESKTOP + "/我的客户.csv", "a", newline='', encoding='utf-8')
我的客户_data_writer = csv.writer(我的客户_data_csvfile)
我的客户_headers = ["姓名", "手机号", "来源", "申请城市", "学历", "户籍", "年龄", "婚姻", "身份证", "性别", "毕业院校", "客户公司", "申请额度", "来源类型",
                "名下房产情况", "名下车产情况", "汽车类型", "汽车归属地", "汽车使用年限", "汽车价值", "车险公司", "当前保单缴费次数", "车辆状态", "BD有无保单", "保单公司",
                "年缴费额", "保单状态", "已缴次数", "两年内最严重的逾期", "一年内最严重的逾期", "半年内最严重的逾期", "微粒贷额度", "芝麻信用分", "信用卡情况", "贷记卡总额总额度",
                "贷记卡当前使用额度", "贷记卡近半年使用额度", "单张贷记卡最高负债率", "有无信用贷款", "客户星级", "状态", "备注", "ID", "员工账号"]
我的客户_count = 0

再分配客户_data_csvfile = open(config.PATH_DESKTOP + "/再分配客户.csv", "a", newline='', encoding='utf-8')
再分配客户_data_writer = csv.writer(再分配客户_data_csvfile)
再分配客户_headers = ["姓名", "手机号", "来源", "申请城市", "学历", "户籍", "年龄", "婚姻", "身份证", "性别", "毕业院校", "客户公司", "申请额度", "来源类型",
                 "名下房产情况", "名下车产情况", "汽车类型", "汽车归属地", "汽车使用年限", "汽车价值", "车险公司", "当前保单缴费次数", "车辆状态", "BD有无保单", "保单公司",
                 "年缴费额", "保单状态", "已缴次数", "两年内最严重的逾期", "一年内最严重的逾期", "半年内最严重的逾期", "微粒贷额度", "芝麻信用分", "信用卡情况", "贷记卡总额总额度",
                 "贷记卡当前使用额度", "贷记卡近半年使用额度", "单张贷记卡最高负债率", "有无信用贷款", "客户星级", "状态", "备注", "ID", "员工账号"]
再分配客户_count = 0

再分配客户_data_writer.writerow(再分配客户_headers)
我的客户_data_writer.writerow(我的客户_headers)


@threads(8)
def get_再分配客户(d, userid, userName):
    try:
        global 再分配客户_count
        global 再分配客户_headers
        global 再分配客户_data_writer
        global 再分配客户_data_csvfile
        # 再分配客户
        url = "https://www.sudai9.com/manage/kefu_clients/edit_client_info.html?id=%s&whichnum=1&page_start=0&is_kefu_againclientslist=1&is_kefu_againclientslist=1&is_kefu_againclientslist_search=&is_again=1&page=1&num=10&&is_again=1" % userid
        response = requestutil.get(url, cookies=d)
        soup = BeautifulSoup(response.text, 'lxml')
        userinfo = _do_detail_page(soup)
        userinfo["手机号"] = get_phone(d, userid)
        userinfo["ID"] = userid
        userinfo["员工账号"] = userName
        # return userinfo
    except:
        userinfo = {}
        userinfo["ID"] = userid
        userinfo["员工账号"] = userName
        # return userinfo

    再分配客户_data_writer.writerow([userinfo[h] for h in 再分配客户_headers])
    if 再分配客户_count > 10:
        再分配客户_data_csvfile.flush()


@threads(4)
def get_我的客户(d, userid, userName):
    try:

        global 我的客户_count
        global 我的客户_headers
        global 我的客户_data_writer
        global 我的客户_data_csvfile

        # 我的客户
        url = "https://www.sudai9.com/manage/kefu_clients/edit_client_info.html?id=%s&whichnum=0&page_start=0&is_myself_kefu=1&is_search_myclients=&search_myself=on&search_again=on&clientFieldValue=&house=&remark=&is_again=0&page=1&num=10&is_hzd=0&&is_again=0" % userid
        response = requestutil.get(url, cookies=d)

        soup = BeautifulSoup(response.text, 'lxml')
        userinfo = _do_detail_page(soup)
        userinfo["手机号"] = get_phone(d, userid)
        userinfo["ID"] = userid
        userinfo["员工账号"] = userName
    except:
        userinfo = {}
        userinfo["ID"] = userid
        userinfo["员工账号"] = userName

    我的客户_data_writer.writerow([userinfo[h] for h in 我的客户_headers])
    print(userid + ":" + userinfo)
    if 我的客户_count > 10:
        我的客户_data_csvfile.flush()


def get_phone(d, userid):
    phone_url = "https://www.sudai9.com/manage/kefu_common/get_mobile.html?id=%s&kid=130871" % userid
    response1 = requestutil.get(phone_url, cookies=d)
    phone = response1.text.replace('{"data":"', "").replace('","msg":"1"}', "")  # {"data":"18115110583","msg":"1"}
    return phone


def do_detail_page(browser):
    # print(browser.page_source)
    soup = BeautifulSoup(browser.page_source, 'lxml')

    # 加载电话号码
    try:
        browser.find_element_by_css_selector(
            "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(2) > div.showdetailsinfo > span").click()
        i = 0
        while i < 10:
            i = i + 1
            time.sleep(0.002)
            phone = get_text(soup,
                             "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(2) > div.showdetailsinfo > span")
            if "点击显示号码" != phone:
                break
    except:
        phone = "异常"
    # print(browser.page_source)

    soup = BeautifulSoup(browser.page_source, 'lxml')
    userinfo = _do_detail_page(soup)

    return userinfo


def _do_detail_page(soup):
    userinfo = {}
    userinfo["姓名"] = get_text(soup,
                              "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(1) > div.showdetailsinfo > textarea")
    userinfo["手机号"] = get_text(soup,
                               "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(2) > div.showdetailsinfo > span")
    userinfo["来源"] = get_text(soup,
                              "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(3) > div.showdetailsinfo")
    userinfo["申请城市"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(4) > div.showdetailsinfo")
    userinfo["学历"] = get_text(soup,
                              "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(5) > div.showdetailsinfo")
    userinfo["户籍"] = get_text(soup,
                              "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(6) > div.showdetailsinfo")
    userinfo["年龄"] = get_text(soup,
                              "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(7) > div.showdetailsinfo")
    userinfo["婚姻"] = get_text(soup,
                              "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(8) > div.showdetailsinfo")
    userinfo["身份证"] = get_text(soup,
                               "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(9) > div.showdetailsinfo")
    userinfo["性别"] = get_text(soup,
                              "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(10) > div.showdetailsinfo")
    userinfo["毕业院校"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(11) > div.showdetailsinfo")
    userinfo["客户公司"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(12) > div.showdetailsinfo")
    userinfo["申请额度"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(13) > div.showdetailsinfo")
    userinfo["来源类型"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(1) > ul > li:nth-child(14) > div.showdetailsinfo")
    userinfo["名下房产情况"] = get_text(soup, "#infomation-info10 > div:nth-child(2) > ul > li > div.showdetailsinfo")
    userinfo["名下车产情况"] = get_text(soup,
                                  "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(1) > div.showdetailsinfo")
    userinfo["汽车类型"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(2) > div.showdetailsinfo")
    userinfo["汽车归属地"] = get_text(soup,
                                 "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(3) > div.showdetailsname")
    userinfo["汽车使用年限"] = get_text(soup,
                                  "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(4) > div.showdetailsinfo")
    userinfo["汽车价值"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(5) > div.showdetailsinfo")
    userinfo["车险公司"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(6) > div.showdetailsinfo")
    userinfo["当前保单缴费次数"] = get_text(soup,
                                    "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(7) > div.showdetailsinfo")
    userinfo["车辆状态"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(8) > div.showdetailsinfo")
    userinfo["BD有无保单"] = get_text(soup,
                                  "#infomation-info10 > div:nth-child(4) > ul > li:nth-child(1) > div.showdetailsinfo")
    userinfo["保单公司"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(4) > ul > li:nth-child(2) > div.showdetailsinfo")
    userinfo["年缴费额"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(4) > ul > li:nth-child(3) > div.showdetailsinfo")
    userinfo["保单状态"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(4) > ul > li:nth-child(4) > div.showdetailsinfo")
    userinfo["已缴次数"] = get_text(soup,
                                "#infomation-info10 > div:nth-child(4) > ul > li:nth-child(5) > div.showdetailsinfo")
    userinfo["两年内最严重的逾期"] = get_text(soup,
                                     "#infomation-info10 > div:nth-child(5) > ul > li:nth-child(1) > div.showdetailsinfo")
    userinfo["一年内最严重的逾期"] = get_text(soup,
                                     "#infomation-info10 > div:nth-child(5) > ul > li:nth-child(2) > div.showdetailsinfo")
    userinfo["半年内最严重的逾期"] = get_text(soup,
                                     "#infomation-info10 > div:nth-child(5) > ul > li:nth-child(3) > div.showdetailsinfo")
    userinfo["微粒贷额度"] = get_text(soup,
                                 "#infomation-info10 > div:nth-child(5) > ul > li:nth-child(4) > div.showdetailsinfo")
    userinfo["芝麻信用分"] = get_text(soup,
                                 "#infomation-info10 > div:nth-child(5) > ul > li:nth-child(5) > div.showdetailsinfo")
    userinfo["信用卡情况"] = get_text(soup,
                                 "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(1) > div.showdetailsinfo")
    userinfo["贷记卡总额总额度"] = get_text(soup,
                                    "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(2) > div.showdetailsinfo")
    userinfo["贷记卡当前使用额度"] = get_text(soup,
                                     "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(3) > div.showdetailsinfo")
    userinfo["贷记卡近半年使用额度"] = get_text(soup,
                                      "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(4) > div.showdetailsinfo")
    userinfo["单张贷记卡最高负债率"] = get_text(soup,
                                      "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(5) > div.showdetailsinfo")
    userinfo["有无信用贷款"] = get_text(soup,
                                  "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(6) > div.showdetailsinfo")
    userinfo["客户星级"] = soup.select("#stars > option[selected=selected]")[0].text
    userinfo["状态"] = soup.select("#status > option[selected=selected]")[0].text

    memo_eles = soup.select("#hisul > li")
    memo_jsons = []
    for m in memo_eles:
        memo_jsons.append(m.text)
    userinfo["备注"] = str(memo_jsons)
    return userinfo


def login(browser, username, pwd):
    logout(browser)
    url = "https://www.sudai9.com/manage/index/indexlogin.html?brand=29"
    browser.get(url)
    browser.find_element_by_css_selector("#kefu_number").send_keys(username)
    browser.find_element_by_css_selector("#smscode").clear()
    browser.find_element_by_css_selector("#kefu_password").clear()
    browser.find_element_by_css_selector("#kefu_password").send_keys(pwd)

    browser.find_element_by_css_selector("#smscode").send_keys("1234")
    browser.find_element_by_css_selector(
        "body > div.container-fluid.login_box > div.container > form > div:nth-child(4) > button").click()
    time.sleep(2)
    if "座席号：" not in browser.page_source:
        # print(browser.page_source)
        print(username + "登陆失败!")
        return False
    else:
        return True


def logout(browser):
    try:
        browser.get("https://www.sudai9.com/manage/index/indexlogout.html")
    except:
        pass


def nextPage(browser):
    try:
        pagenums = browser.find_elements_by_css_selector("#pagination > a")

        current_p = None
        for p in pagenums:
            if current_p:
                p.click()
                return True
            if p.get_attribute("outerHTML"):
                current_p = p
        return False
    except Exception as e:
        return False


def search(browser, menu_name, tag, userName):
    to_main(browser)

    cks = browser.get_cookies()
    ck_dict = requestutil.cookie_dict_from_list(cks)

    click_menu(browser, menu_name)
    time.sleep(3)
    for i in range(1, 1000):
        print(menu_name + "页码:" + str(i))
        to_target_page(browser, tag)
        time.sleep(3)
        trs = browser.find_elements_by_css_selector("#lk_content > table > tbody > tr")
        print("行数:" + str(len(trs)))
        for tr in trs:
            try:
                to_target_page(browser, tag)
                tr_html = tr.get_attribute("innerHTML")
                if "Open" not in tr_html:
                    continue

                a = tr.find_elements_by_css_selector("td")[2].get_attribute("outerHTML")
                a = a.replace("&amp;", "&")
                userid = re.search("edit_client_info.html\?id=(.*)&whichnum=", a).group(1)
                print(userid)
                if "我的客户" == menu_name:
                    r = get_我的客户(ck_dict, userid, userName)
                if "再分配客户" == menu_name:
                    r = get_再分配客户(ck_dict, userid, userName)



            except Exception as e:
                traceback.print_exc()

        if not nextPage(browser):
            break
    time.sleep(10)


def execute(browser, username, pwd):
    print(username)
    if not login(browser, username, pwd):
        return

    try:
        search(browser, "我的客户", "/manage/kefu_clients/index.html", username)
        search(browser, "再分配客户", "/manage/kefu_againclientslist/index.html", username)
    except Exception as e:
        traceback.print_exc()


def eee(users1):
    users = json.loads(users1)
    browser = seleniumutil.chrome_driver_remote()
    for u in users:
        try:
            execute(browser, u[0], u[1])
        except:
            traceback.print_exc()
    我的客户_data_csvfile.flush()
    我的客户_data_csvfile.close()
    再分配客户_data_csvfile.flush()
    再分配客户_data_csvfile.close()


if __name__ == "__main__":
    # eee()
    a = """
    
    <td onclick="Open('邵其冰','/manage/kefu_clients/edit_client_info.html?id=4701187&amp;whichnum=38&amp;page_start=0&amp;is_myself_kefu=1&amp;is_search_myclients=&amp;search_myself=on&amp;search_again=on&amp;clientFieldValue=&amp;house=&amp;remark=&amp;is_again=0&amp;page=1&amp;num=200&amp;is_hzd=0&amp;');" title="点击修改客户信息">
									邵其冰
								</td>
    """
    a = a.replace("&amp;", "&")
    # a = re.search("','/(.*)" + "[');\" title=]", a).group(1).replace("');\" title=\"点击修改客户信息", "")
    # a = "https://www.sudai9.com/" + a
    userid = re.search("edit_client_info.html\?id=(.*)&whichnum=", a).group(1)
    print(a)
